//
//  JoinMeetingViewController.swift
//  visionos_test_demo
//
//  Created by 3tee on 2024/7/25.
//

import UIKit
import rtc_sdk_vision
import SwiftUI

 

class JoinMeetingViewController: UIViewController {

    @IBOutlet weak var roomTf: UITextField!
    
    @IBOutlet weak var nameTf: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initEngine()
        roomTf.text = "10000000000"
        nameTf.text = "visionOS"
        // Do any additional setup after loading the view.
    }

    func initEngine(){
        var serURL = ""
        if let serverUrl = UserDefaults.standard.string(forKey: K.urlKey) {
            serURL = serverUrl
        }else{
            serURL = K.url
        }
        AVDEngine.instance().initWithServerUrl(serURL, accessKey: K.appKey, secretKey: K.secretKey, delegate: self)
        let logpath = logFilePath()
        AVDEngine.instance().setLogParams("info", file: logpath)
    }
    
    func logFilePath() -> String {
        let dateFormat = DateFormatter()
         dateFormat.dateFormat = "yyyy-MM-dd-HHmmss"
        let dateString = dateFormat.string(from: Date())
        let fileName = "\(dateString)_log.txt"
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        var documentPath = paths[0]
        documentPath  = documentPath + "/" + fileName
        return  documentPath
        
    }
    
    func createRoom() {
        let roomInfo = AVDRoomInfo(roomId: self.roomTf.text, roomName: "按照需求", appRoomId: self.roomTf.text, ownerId: nil, maxAttendee: 5, maxAudio: 5, maxVideo: 5, roomMode: 0, voiceActivated: true)
        roomInfo?.setRoomModeFlag(AVDRoomMode(mcu.rawValue))
        AVDEngine.instance().scheduleRoom(roomInfo)
    }
   
    @IBAction func joinMeetingClicked(_ sender: UIButton) {
        
        let room = AVDRoom.obtain(roomTf.text);
        let user = AVDUser(userId: UUID().uuidString, userName:nameTf.text , userData: nil)
        room?.join(with: user, delegate: self)
       
    }
    @IBAction func settingClicked(_ sender: UIButton) {
        let setVC = SettingViewController()
        setVC.delegate  = self
        navigationController?.pushViewController(setVC, animated: true)
    }
    
}



extension JoinMeetingViewController: SettingViewControllerDelegate{
    func reInitEng(url: String) {
        AVDEngine.instance().uninit()
        AVDEngine.instance().initWithServerUrl(url, accessKey:K.appKey, secretKey: K.secretKey, delegate: self)
    }
    
}

extension JoinMeetingViewController: AVDEngineDelegate{
    func onInitResult(_ result: AVDResult) {
        print("onInitResult = \(result)")
        var msg = ""
        if result == AVD_Success {
            msg = "✅✅✅✅初始化引擎成功✅✅✅✅"
        }else{
            msg = "❌❌❌❌引擎初始化失败❌❌❌❌ code = \(result)"
        }
        AlertTool().show(msg, in: self.view)
    }
    
    func onScheduleRoomResult(_ result: AVDResult, roomId: String!) {
        var msg = ""
        if result == AVD_Success {
            msg = "✅✅✅✅房间创建成功✅✅✅✅"
        }else{
            msg = "❌❌❌❌房间创建失败❌❌❌❌"
        }
        AlertTool().show(msg, in: self.view)
    }
}

extension JoinMeetingViewController: AVDRoomJoinDelegate{
    func onJoinResult(_ aResult: AVDResult) {
        var msg = ""
        if aResult == 0 {
            msg =  "✅✅✅✅房间加入成功✅✅✅✅"
            UserDefaults().setValue(roomTf.text, forKey:K.roomId)
            self.navigationController?.pushViewController(MeetingViewController(), animated: true)
        } else {
            print("加入房间失败 = \(aResult)")
            msg = "❌❌❌❌房间加入失败❌❌❌❌"
        }
        //AlertTool().show(msg, in: self.view)
        AlertTool.alertShow(msg, alertVC: self)
    }
}
